package telbook;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AddServlet
 */
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");//传值编码
		response.setContentType("text/html;charset=UTF-8");
		String name=request.getParameter("name");
		String number=request.getParameter("number");
		String address=request.getParameter("address");
		String qq=request.getParameter("qq");
		String table=null;
		Connection conn=null;
		Statement stmt=null;
		ResultSet rs=null;
		try {
//			获取数据连接
			conn=JDBCUtils.getConnection();
//			获取Statement对象
			stmt=conn.createStatement();
			Object accunt=null;
			Cookie[]cookies=request.getCookies();
			for(int i=0;cookies!=null&&i<cookies.length;i++)
			{
				if("userbean".equals(cookies[i].getName())){
					accunt=cookies[i].getValue();
					break;
				}
			}
//			发送SQL语句
			String sql="select tables from users where name='"+accunt+"'";
			rs=stmt.executeQuery(sql);
			while(rs.next()) {
				table=rs.getString("tables");
			}
			sql="INSERT INTO `telbook`.`"+
			table+"`(`name`, `number`, `address`, `qq`) VALUES ('"+
			name+"', '"+number+"', '"
			+address+"', '"+qq+"')";
			stmt.execute(sql);
			request.setAttribute("DBMes", "<p style='color:green'>添加成功</p>");
			request.getRequestDispatcher("/add.jsp")
			.forward(request, response);
		}catch(Exception e) {
			e.printStackTrace();
			request.setAttribute("DBMes", "您添加的信息已存在");
			request.getRequestDispatcher("/add.jsp")
			.forward(request, response);
			
		}finally {
			JDBCUtils.release(rs, stmt, conn);
		}
	}

}
